package com.example.interview.common;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName Common
 * @Description TODO
 * @Author mengq
 * @Date 2021/2/26 21:40
 **/
@Slf4j
public class Common {
    private static ConcurrentHashMap<String, ChatRoom> chatRoomMap = new ConcurrentHashMap<String, ChatRoom>();
    private static ConcurrentHashMap<String, Person> userMap = new ConcurrentHashMap<String, Person>();

    public static String joinRoom(String roomId, String userId) {
        ChatRoom chatRoom = chatRoomMap.get(roomId);
        Person person = userMap.get(userId);
        if (null != chatRoom && null != person) {
            return chatRoom.add(userId, person);
        }
        return "房间号或者用户不存在！";
    }

    public static String leaveRoom(String roomId, String userId) {
        ChatRoom chatRoom = chatRoomMap.get(roomId);
        Person person = userMap.get(userId);
        if (null != chatRoom && null != person) {
            return chatRoom.remove(userId, person);
        }
        return "房间号或者用户不存在！";
    }

    public static String createRoom(String roomId) {
        ChatRoom old = chatRoomMap.get(roomId);
        String res;
        if (null == old) {
            chatRoomMap.put(roomId, new ChatRoom(roomId));
            res = "已创建房间 " + roomId;
            log.info(res);
        } else {
            res = "已存在房间 " + roomId;
        }
        return res;
    }

    public static String createPerson(String userId) {
        Person old = userMap.get(userId);
        String res;
        if (null == old) {
            userMap.put(userId, new Person(userId));
            res = "已创建游客 " + userId;
            log.info(res);
        } else {
            res = "已存在游客 " + userId;
        }
        return res;
    }
}
